package com.wzh.sending;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.wzh.sending.adapter.AllUserAdapter;
import com.wzh.sending.callback.LocationInterface;
import com.wzh.sending.info.LocationInfo;
import com.wzh.sending.info.UsersInfo;
import com.wzh.sending.utils.LocationUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.BmobUpdateListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.update.BmobUpdateAgent;
import cn.bmob.v3.update.UpdateResponse;
import cn.bmob.v3.update.UpdateStatus;

public class UserActivity extends CheckPermissionsActivity {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.my_list)
    ListView myList;
    @Bind(R.id.my_srf)
    SwipeRefreshLayout mySrf;

    List<LocationInfo> locationInfos;
    AllUserAdapter allUserAdapter;
    double lot = 0;
    double lat = 0;
    Intent intent;
    LocationUtil locationUtil;
    UsersInfo usersInfo;
    @Bind(R.id.progress)
    ProgressBar progress;
    @Bind(R.id.see_all)
    TextView seeAll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_user);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        intent = getIntent();
        myList.setEmptyView(progress);
        usersInfo = (UsersInfo) intent.getSerializableExtra("user");
        if (TextUtils.isEmpty(usersInfo.getName())) {
            if (TextUtils.isEmpty(usersInfo.getLineNo())) {
                setBarTitle(toolbar, usersInfo.getImeiNo());
            } else {
                setBarTitle(toolbar, usersInfo.getLineNo());
            }
        } else {
            setBarTitle(toolbar, usersInfo.getName());
        }
        locationUtil = new LocationUtil(this);
        locationUtil.initLocation();
        locationInfos = new ArrayList<>();
        allUserAdapter = new AllUserAdapter(getBaseContext(), locationInfos);
        myList.setAdapter(allUserAdapter);
        locationUtil.setLocationInterface(new LocationInterface() {
            @Override
            public void getLocation(AMapLocation loc) {
                if (loc != null) {
                    lat = loc.getLatitude();
                    lot = loc.getLongitude();
                    allUserAdapter.setLotandLat(lot, lat);
                    locationUtil.stopLocation();
                    locationUtil.destroyLocation();
                    check(usersInfo);
                } else {
                    mySrf.setRefreshing(false);
                }
            }
        });
        locationUtil.startLocation();
        initEvent();
    }

    private void initEvent() {
        mySrf.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                locationUtil.initLocation();
                locationUtil.startLocation();
                locationInfos.clear();
                allUserAdapter.notifyDataSetChanged();
            }
        });
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (TextUtils.isEmpty(locationInfos.get(i).getAddRess())) {
                    GeocodeSearch geocoderSearch = new GeocodeSearch(getBaseContext());//传入context
                    LatLonPoint latLonPoint = new LatLonPoint(locationInfos.get(i).getLatitude(), locationInfos.get(i).getLongitude());
                    // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
                    RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 100, GeocodeSearch.AMAP);
                    geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                        @Override
                        public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                            if (i == 1000) {
                                if (regeocodeResult != null && regeocodeResult.getRegeocodeAddress() != null
                                        && regeocodeResult.getRegeocodeAddress().getFormatAddress() !=
                                        null) {
                                    Toast.makeText(getBaseContext(), regeocodeResult.getRegeocodeAddress().getFormatAddress() +
                                            "附近", Toast.LENGTH_LONG).show();
                                } else {
                                    List<PoiItem> poiItems = regeocodeResult.getRegeocodeAddress().getPois();
                                    for (PoiItem poiItem : poiItems) {

                                        Log.e("zhangzida", poiItem.getTitle());//输出周边poi的信息
                                    }
                                }

                            } else {
                                Toast.makeText(getBaseContext(), "位置太偏暂时查询不到道路信息。", Toast.LENGTH_LONG).show();

                            }
                        }

                        @Override
                        public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

                        }
                    });
                    geocoderSearch.getFromLocationAsyn(query);
                }
            }
        });


    }

    private void check(UsersInfo usersInfo) {
        Log.e("imeiNo", usersInfo.getImeiNo() + "");
        BmobQuery<LocationInfo> query = new BmobQuery<LocationInfo>();
        query.addWhereEqualTo("imeiNo", usersInfo.getImeiNo());
        Date curDate = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String start = sdf.format(curDate);
        Date date = null;
        try {
            date = sdf.parse(start);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        query.addWhereGreaterThan("createdAt", new BmobDate(date));
        query.setLimit(800);
        query.findObjects(new FindListener<LocationInfo>() {
            @Override
            public void done(List<LocationInfo> list, BmobException e) {
                mySrf.setRefreshing(false);
                if (e == null) {
                    if (list.size() != 0) {
                        locationInfos.addAll(list);
                        Collections.reverse(locationInfos);
                        allUserAdapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(getBaseContext(), "今日暂无定位信息。", Toast.LENGTH_LONG).show();
                        progress.setVisibility(View.GONE);
                    }

                } else {
                    Log.e("E", e.getMessage());
                }
            }
        });

    }
    @OnClick(R.id.see_all)
    public void setSeeAll() {
        intent.setClass(this,TrackActivity.class);
        startActivity(intent);
    }
}
